package com.example.demo.netty.udp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by shangfei on 2018/7/10.
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {

        //1、接收连接请求
        EventLoopGroup pGroup = new NioEventLoopGroup();
        //2、实际的业务处理操作
        EventLoopGroup cGroup = new NioEventLoopGroup();

        //3、创建一个辅助类bootpcstrap，对Server进行一系列配置
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //把两个工作线程组加入进来
        serverBootstrap.group(pGroup, cGroup)
                .channel(NioServerSocketChannel.class)//指定使用NioServerSocketChannel类型的通道
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_SNDBUF, 32 * 1024)
                .option(ChannelOption.SO_RCVBUF, 32 * 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture channelFuture = serverBootstrap.bind(8765).sync();

        channelFuture.channel().closeFuture().sync();

        pGroup.shutdownGracefully();
        cGroup.shutdownGracefully();
    }
}
